package com.fang.dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.fang.entity.User;
import com.fang.utils.JDBCUtils;

public class UserDao {

	public User queryUser(User user) {
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "select * from user where username=?";
		try {
			return qr.query(sql, new BeanHandler<User>(User.class),user.getUsername());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("注册异常"+e);
		}
	}

	public void addUser(User user) {
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "insert into user values(null,?,?,?,?,?,?,?)";
		try {
			qr.update(sql,user.getUsername(),user.getPassword(),user.getNickname(),user.getEmail(),
					user.getTelephone(),user.getCode(),0);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("添加用户异常"+e);
		}
		
	}

	public void active(String code) {
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "update user set status = 1 where code=?";
		try {
			qr.update(sql, code);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("激活邮箱错误"+e);
		}
		
		
	}

	public User loginUser(User user) {
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "select * from user where username=? and password=?";
		try {
			return qr.query(sql, new BeanHandler<User>(User.class), user.getUsername(),user.getPassword());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("登录失败"+e);
		}
	}

}
